package com.yuan.ocr.tess4j;

import com.yuan.ocr.common.OcrConst;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import net.sourceforge.tess4j.util.LoadLibs;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @author YouYuan
 * @version 1.0
 * @Email xiyousuiyuan@163.com
 * @Date 2018/10/28 16:37
 */
public class Tess4jOCR {

    private static String TESSDATA_FOLDER = LoadLibs.extractTessResources("tessdata").getAbsolutePath();

    static {
        ImageIO.scanForPlugins();
    }

    /**
     * 识别文字,默认设置英文字库,使用classpath目录下的tessdata训练库
     *
     * @param img
     * @return
     */
    public static String doOCR(String img) {
        ITesseract instance = new Tesseract();
        File imageFile = new File(img);
        instance.setDatapath(TESSDATA_FOLDER);
        instance.setLanguage(OcrConst.LANGUAGE_ENG);
        try {
            return instance.doOCR(imageFile);
        } catch (TesseractException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据指定的语言和训练库识别文字
     * @param filePath 需要识别的文件
     * @param tessdataPath 训练库路径
     * @param language 语言（值为训练库文件的前缀，Tess4jConst中的值）
     * @return
     */
    public static String doOCR(String filePath, String tessdataPath, String language) {
        ITesseract instance = new Tesseract();
        File imageFile = new File(filePath);
        instance.setDatapath(tessdataPath);
        instance.setLanguage(language);
        try {
            return instance.doOCR(imageFile);
        } catch (TesseractException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String doOCR(String filePath, String language) {
        return doOCR(filePath, TESSDATA_FOLDER, language);
    }

    public static String doOCR(BufferedImage bufferedImage, String tessdataPath, String language) {
        ITesseract instance = new Tesseract();
        instance.setDatapath(tessdataPath);
        instance.setLanguage(language);
        ImageIO.scanForPlugins();
        try {
            return instance.doOCR(bufferedImage);
        } catch (TesseractException e) {
            e.printStackTrace();
            return null;
        }
    }

}
